package com.romin.aplication;


import com.romin.crawler.MeipaiCrawler;
import com.romin.dao.AdvertisementDao;
import com.romin.dao.ArticleDao;
import com.romin.dao.ManagerDao;
import com.romin.dao.ShortVideoDao;
import com.romin.pojo.Advertisement;
import com.romin.pojo.Article;
import com.romin.pojo.Manager;
import com.romin.pojo.ShortVideo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.model.OOSpider;
import us.codecraft.webmagic.pipeline.PageModelPipeline;

/**
 * @author cloud.eve
 */
@SpringBootApplication(scanBasePackages = "com.romin")
@EnableJpaRepositories("com.romin.dao")
@EntityScan("com.romin.pojo")
public class MainApplication extends SpringBootServletInitializer {


    public static final Logger log = LoggerFactory.getLogger(MainApplication.class);

    public static void main(String[] args) throws Exception {
        SpringApplication.run(MainApplication.class);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(MainApplication.class);
    }

    @Bean
    public RepositoryRestConfigurer repositoryRestConfigurer() {

        return new RepositoryRestConfigurerAdapter() {
            @Override
            public void configureRepositoryRestConfiguration(
                    RepositoryRestConfiguration config) {
                config.exposeIdsFor(Article.class, Advertisement.class);
            }
        };

    }

    @Bean
    public CommandLineRunner initManager(final ManagerDao managerDao) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                /**
                 * 管理用户
                 */
                managerDao.save(new Manager("luozhiming", "25252525", 2));
                managerDao.save(new Manager("admin", "admin", 1));
                managerDao.save(new Manager("admin1", "admin", 1));
                managerDao.save(new Manager("admin2", "admin", 1));
                managerDao.save(new Manager("admin3", "admin", 1));
                managerDao.save(new Manager("admin4", "admin", 1));
                managerDao.save(new Manager("admin5", "admin", 1));
                managerDao.save(new Manager("admin6", "admin", 1));
                managerDao.save(new Manager("admin7", "admin", 1));
                managerDao.save(new Manager("admin8", "admin", 1));
                managerDao.save(new Manager("admin9", "admin", 1));
                managerDao.save(new Manager("admin10", "admin", 1));
                managerDao.save(new Manager("admin11", "admin", 1));

            }
        };
    }

    @Bean
    public CommandLineRunner initAdvertisement(final AdvertisementDao advertisementDao, final ArticleDao articleDao) {

        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                Advertisement advertisement = new Advertisement();
                advertisement.setName("人流广告");
                advertisement.setImage("http://www.baidu.com/logo.gif");
                advertisement.setTargetUrl("http://www.baidu.com");
                advertisement.setDesc("无痛人流请到xx门诊");
                advertisementDao.save(advertisement);

                Advertisement advertisement1 = new Advertisement();
                advertisement1.setName("考研广告");
                advertisement1.setImage("http://www.baidu.com/logo.gif");
                advertisement1.setTargetUrl("http://www.baidu.com");
                advertisement1.setDesc("学历不够？想考研，去中科院大学攻读在职研究生，分分钟拿到学历证书");
                advertisementDao.save(advertisement1);

                Advertisement advertisement2 = new Advertisement();
                advertisement2.setName("优酷图片广告");
                advertisement2.setImage("http://r3.ykimg.com/05100000572317FA67BC3D7EAF027857");
                advertisement2.setTargetUrl("http://www.youku.com");
                advertisementDao.save(advertisement2);


                /**
                 * 管理文章
                 */
                String content = "";
                for (int i = 0; i < 10; i++) {
                    Article article = new Article();
                    article.setTitle("如何更高效的学习" + i);
                    article.setCategory("未分类");
                    content = "如何更加高效的学习，如何更加高效的学习" + i;
                    article.setContent(content);
                    if (i < 3) {
                        Advertisement advert = advertisementDao.findOne((long) (i + 1));
                        article.setAdvertisement(advert);
                        System.out.println(advert.getName());
                    }
                    articleDao.save(article);
                }

            }
        };
    }

    @Bean
    public CommandLineRunner initCrawler(final ShortVideoDao shortVideoDao) {

        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                Spider spider = OOSpider.create(Site.me().setSleepTime(1000).setRetryTimes(2).setTimeOut(1000).setUserAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36")
                        , new PageModelPipeline<MeipaiCrawler>() {
                            @Override
                            public void process(MeipaiCrawler o, Task task) {
                                if (StringUtils.isNotEmpty(o.getVid())) {
                                    ShortVideo v = new ShortVideo();
                                    v.setVid(o.getVid());
                                    v.setCategory(o.getCategory());
                                    v.setDesc(o.getDesc());
                                    v.setSite(1);
                                    v.setUserId(o.getUserId().substring(27, o.getUserId().length()));
                                    v.setUserName(o.getUserName());
                                    v.setUrl("http://www.meipai.com/media/" + o.getVid());
                                    shortVideoDao.save(v);
                                    //跑一万条数据，跑够了就不管了
                                }
                            }
                        }, MeipaiCrawler.class)
                        .addUrl("http://www.meipai.com/media/613978422").thread(10);
                spider.setExitWhenComplete(true);
                spider.runAsync();
            }
        };
    }

}